package com.xsz.pda.net.udp;
 
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Jason on 2016/5/18.
 */
public class UdpServer implements Runnable {

    private static final String TAG = "UDPHelper";

    private final String ip ;
    private final int port;
    private static DatagramSocket ds = null;
    private final byte[] msgRcv = new byte[3 * 1024 * 1024];
    private boolean udpLife = true;

    private final ConcurrentHashMap<Integer, OnMsgCallback> msgListenerMap = new ConcurrentHashMap<>();

    public UdpServer(String mIp, int mPort) {
        this.ip = mIp;
        this.port = mPort;
    }


    void setMsgListener(int what, OnMsgCallback msgListener) {
        msgListenerMap.put(what, msgListener);
    }




    public void stop(){
        udpLife = false;
    }



    @Override
    public void run() {
        InetSocketAddress inetSocketAddress = new InetSocketAddress(ip, port);
        try {
            ds = new DatagramSocket(inetSocketAddress);
            Log.i(TAG, "UDP服务器已经启动");
        } catch (SocketException e) {
            e.printStackTrace();
        }

        DatagramPacket dpRcv = new DatagramPacket(msgRcv, msgRcv.length);
        Log.i("UDPHelper", "启动成功");
        while (udpLife) {
            try {
                ds.receive(dpRcv);
            } catch (IOException e) {
                Log.e(TAG, "接收消息异常", e);
            }
            String json = new String(dpRcv.getData(), dpRcv.getOffset(), dpRcv.getLength());

            Map<String, Object> info;
            try {
                info = JSON.parseObject(json, new TypeReference<Map<String,Object>>() {}.getType());
                Log.d(TAG, "recv from " + dpRcv.getAddress().getHostAddress() + "：" + info.get("what"));
            }catch (Exception e){
                Log.e(TAG, "解析错误消息", e);
                continue;
            }
            int what = (int) info.get("what");
            OnMsgCallback listener = msgListenerMap.get(what);
            if (listener!=null) {
                listener.onMessage(JSON.toJSONString(info.get("data")), dpRcv.getAddress().getHostAddress());
            }
        }
        ds.close();
        Log.i("UDPHelper","UDP监听关闭");
    }
}